package centerberg.game;

import centerberg.engine.Engine;

import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
import java.util.HashMap;
import java.util.Map;

/**
 * Class handling key presses and keeping the state of
 * buttons that are relevant.
 * 
 * @author Andreas Svanberg
 */
public class Keys extends KeyAdapter
{
    /**
     * The key for going left.
     */
    public static final Key left = new Key();
    
    /**
     * The key for going right.
     */
    public static final Key right = new Key();
    
    /**
     * The key to jump.
     */
    public static final Key jump = new Key();
    
    /**
     * The key to transform.
     */
    public static final Key transform = new Key();
    
    private Map<Integer, Key> bindings = new HashMap<Integer, Key>();
    
    private Keys()
    {
        loadDefaultBinds();
    }
    
    /**
     * Handles key releases and updates the pressed state
     * if the button is binded.
     * 
     * @param event the keyevent
     */
    public void keyReleased(KeyEvent event)
    {
        if (bindings.containsKey(event.getKeyCode()))
            bindings.get(event.getKeyCode()).setDown(false);
    }
    
    /**
     * Handles key presses and updates the pressed state
     * if the button is binded.
     * 
     * @param event the keyevent
     */
    public void keyPressed(KeyEvent event)
    {
        if (bindings.containsKey(event.getKeyCode()))
            bindings.get(event.getKeyCode()).setDown(true);
    }
    
    /**
     * Loads the default binds.
     */
    private void loadDefaultBinds()
    {
        bindings.put(KeyEvent.VK_LEFT, left);
        bindings.put(KeyEvent.VK_RIGHT, right);
        bindings.put(KeyEvent.VK_SPACE, jump);
        bindings.put(KeyEvent.VK_D, transform);
    }
    
    /**
     * When this class is loaded, attach to the engine.
     */
    static
    {
        Engine.getInstance().addKeyListener(new Keys());
    }
    
    /**
     * Simple data class storing key states.
     */
    public static class Key
    {
        private boolean isDown;
        
        /**
         * Returns the pressed state of this key.
         * 
         * @return pressed state
         */
        public synchronized boolean isDown()
        {
            return isDown;
        }
        
        /**
         * Sets the pressed state of this key.
         * 
         * @param down the pressed state
         */
        public synchronized void setDown(boolean down)
        {
            isDown = down;
        }
    }
}